import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth.js'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {

    userLogin(store, payload) {
      return new Promise((resolve, reject) => {
        login(payload).then(res => {
          store.commit('setToken', res.data)
          resolve()
        })
      })
    },
    // 获取用户资料
    asyncUserInfo(store, payload) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          console.log(res)
          getUserDetailById(res.data.userId).then(newres => {
            console.log(newres)
            store.commit('setUserInfo', { ...res.data, ...newres.data })
            resolve(res)
          })
        })
      })
    },
    // 退出登录
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserInfo')
    }
  }
}
